// index.js

import {getUser, setUser, setUserPlaylist} from "../../store/user"
import {getMusics} from "../../lib/music";
import {audioCtx} from "../../store/constants";
import {getPlay, setPlay, uptPlay} from "../../store/play";
import {
    getMusicIdx,
    getPlayList,
    getRecommendList,
    setMusicIdx,
    setPlayList,
    setRecommendList
} from "../../store/playlist";

// 获取应用实例
const app = getApp()

Page({
    data: {
        item: 0,
        tab: 0,

        // 播放器列表数据 todo: 提取到store全局
        playlist: [
            // {
            //     id: 1,
            //     title: "晴天",
            //     singer: '周杰伦',
            //     src: 'http://localhost:3000/audio/可惜没如果-林俊杰.320.mp3',
            //     coverImgUrl: 'http://localhost:3000/cover/可惜没如果.webp'
            // },
            // {
            //     id: 2,
            //     title: "反方向的钟",
            //     singer: '周杰伦',
            //     src: 'http://localhost:3000/audio/江南-林俊杰.320.mp3',
            //     coverImgUrl: 'http://localhost:3000/cover/江南.webp'
            // },
        ],
        // 推荐歌曲列表
        recommendList: [],
        state: 'paused', /*播放状态码*/
        playIndex: 0,
        play: {
            currentTime: '00:00',
            duration: '00:00',
            percent: 0,
            title: '',
            singer: '',
            coverImgUrl: '',
        },
    },

    // 跳转
    toSearch(e) {
        wx.reLaunch({url: '../search/search'})
    },

    /*滚动条js函数*/
    sliderChange: function (e) {
        var second = e.detail.value * audioCtx.duration / 100
        console.log(second)
        // ?
        uptPlay({duration: this.formatTime(second)})
        console.log(getPlay())
        audioCtx.seek(second)
    },
    /*播放/暂停音乐js函数*/
    play: function () {
        audioCtx.play()
        this.setData({state: 'running'})
    },
    pause: function () {
        audioCtx.pause()
        this.setData({state: 'paused'})
    },

    // 当前音乐
    // audioCtx: null,

    /*播放列表键,点击切换音乐 */
    change: function (e) {
        // 设置新index
        setMusicIdx(e.currentTarget.dataset.index)
        console.log(getMusicIdx())
        // 播放当前歌单的 指定索引的 歌
        this.setMusic(getMusicIdx())
        this.play()
    },
    /*推荐列表,点击切换音乐 */
    recommendChange (e) {
        // 设置播放列表为推荐列表
        setPlayList(getRecommendList())
        this.setData({
            playlist: getRecommendList()
        })
        console.log(getRecommendList())
        // 设置新index
        setMusicIdx(e.currentTarget.dataset.index)
        console.log(getMusicIdx())
        // 播放当前歌单的 指定索引的 歌
        this.setMusic(getMusicIdx())
        this.play()
    },

// 切走要停止播放 ?
//     onUnload() {
//         console.log(1)
//         audioCtx = null
//         audioCtx.src=''
//     },

    //格式化时间
    formatTime(time) {
        var minute = Math.floor(time / 60) % 60;
        var second = Math.floor(time) % 60;
        return (minute < 10 ? '0' + minute : minute) + ':' + (second < 10 ? '0' + second : second)
    },
    onReady: function (index) {
        var that = this
        //播放失败检测
        audioCtx.onError(function () {
            console.log('播放失败：' + audioCtx.src)
        })
        //播放结束后自动换下一曲
        audioCtx.onEnded(function () {
            that.next()
        })
        //自动更新播放速度
        audioCtx.onPlay(function () {
        })
        audioCtx.onTimeUpdate(function () {
            // that.setData({
            //     'play.duration': formatTime(that.audioCtx.duration),
            //     'play.currentTime': formatTime(that.audioCtx.currentTime),
            //     'play.percent': that.audioCtx.currentTime / that.audioCtx.duration * 100
            // })
            console.log(1)
            uptPlay({
                duration: that.formatTime(audioCtx.duration),
                currentTime: that.formatTime(audioCtx.currentTime),
                percent: audioCtx.currentTime / audioCtx.duration * 100
            })
            that.setData({
                play: getPlay()
            })
            console.log(getPlay())
        })
        // 默认选择第一曲
        // this.setMusic(0)
        // 提取全局id后, 可以全局使用, 随着search页改变, 也能获取最新的索引
        this.setMusic(getMusicIdx())
    },

    // 设置当前播放的音乐信息
    setMusic: function (index) {
        console.log(index)
        // var music = this.data.playlist[index]
        var music = getPlayList()[index]
        audioCtx.src = music.src
        this.setData({
            playIndex: index,
            //     'play.title': music.title,
            //     'play.singer': music.singer,
            //     'play.coverImgUrl': music.coverImgUrl,
            //     'play.currentTime': '00:00',
            //     'play.duration': '00:00',
            //     'play.percent': 0
        })
        setPlay({
            title: music.title,
            singer: music.singer,
            coverImgUrl: music.coverImgUrl,
            currentTime: '00:00',
            duration: '00:00',
            percent: 0
        })
        this.setData({
            play: getPlay()
        })
        // console.log(this.data.play)
    },

    next: function () {
        audioCtx.stop()
        // var index = this.data.playIndex >= this.data.playlist.length - 1 ? 0 : this.data.playIndex + 1
        var index = getMusicIdx() >= getPlayList().length - 1 ? 0 : getMusicIdx() + 1
        setMusicIdx(index)

        this.setMusic(index)
        if (this.data.state === 'running') {
            this.play()
        }
    },

    changeItem: function (e) {
        // console.log(e.target.dataset.item)
        this.setData({
            item: e.target.dataset.item
        })
    },

    changePage: function (e) {
        this.setData({
            item: e.target.dataset.page
        })
    },

    // 改变index页面的顶部导航index
    changeTab: function (e) {
        this.setData({
            tab: e.detail.current
        })
    },

    // 页面加载
    onLoad() {
        // 搜索页回来, 获取最新play
        this.setData({
            play: getPlay()
        })
        console.log(getPlay())
        if (getPlayList().length <= 0) {
            // 获取音乐列表
            getMusics((res) => {
                // console.log(res)
                this.setData({
                    playlist: res.data.musics
                })
                // 更新?
                setPlayList(res.data.musics)
                this.setData({
                    recommendList: this.data.playlist.slice(0, 6)
                })
                setRecommendList(this.data.recommendList)
            })
        }
        // 如果已经有列表(别处改变了), 就用当前列表
        this.setData({
            playlist: getPlayList(),
            recommendList: getRecommendList()
        })

        let userInfo = getUser()
        if (userInfo) {
            this.setData({
                userInfo,
                hasUserInfo: true
            })
            // setUserPlaylist(userInfo.musicList)
        } else if (this.data.canIUse) {
            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
            // 所以此处加入 callback 以防止这种情况
            // app.userInfoReadyCallback = res => {
            //     this.setData({
            //         userInfo: res.userInfo,
            //         hasUserInfo: true
            //     })
            // }
        } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            // wx.getUserInfo({
            //     success: res => {
            //         app.globalData.userInfo = res.userInfo
            //         this.setData({
            //             userInfo: res.userInfo,
            //             hasUserInfo: true
            //         })
            //     }
            // })
        }
    },
    // getUserInfo(e) {
    //     console.log(e)
    //     app.globalData.userInfo = e.detail.userInfo
    //     this.setData({
    //         userInfo: e.detail.userInfo,
    //         hasUserInfo: true
    //     })
    // }
})
